﻿@{
    ViewBag.Title = "TestWebSocket";
}

<script type="text/javascript">
    function connect(url) {
        var ws = new WebSocket(url);
        ws.onmessage = function (evt) {
            var obj = JSON.parse(evt.data);
            var mainDiv = document.querySelector("#main ul");
            var subDiv = document.createElement("li");
            subDiv.innerHTML = "<span>Message: " + obj.Name + "</span><span>Time: " + obj.Time + "</span>";
            mainDiv.appendChild(subDiv);
        };
        ws.onopen = function () {
            console.log('client opend at ' + new Date());
        };
        ws.onclose = function () {
            console.log('client closed at ' + new Date());
            console.log("trying to reconnect....");
            //when iis session time out we need to active it first by request a file
            var intervalId = setInterval(function () {
                ajaxRequest("/", function () {
                    clearInterval(intervalId);
                    connect(url);
                });

            }, 5000);
        }
    }

    function ajaxRequest(url, callback) {
        $.ajax({
            url: url,
            async: false
        }).done(function (data) {
            if (callback) {
                callback(data);
            }
        }).fail(function (e) {
        })
    }
    connect("ws://localhost:9999/WebSocketDemo");

</script>

<div id="main">
    <ul></ul>
</div>


